package com.leejxx.health.service.impl;

import com.leejxx.health.common.MessageConst;
import com.leejxx.health.dao.OrderDao;
import com.leejxx.health.dao.OrderSettingDao;
import com.leejxx.health.exception.BusinessRuntimeException;
import com.leejxx.health.pojo.Order;
import com.leejxx.health.pojo.OrderSetting;
import com.leejxx.health.service.OrderService;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;

/**
 * @Author LeeJx
 * @ClassName OrderServiceImpl
 * @Description TODO
 * @date 2021/1/6 14:59
 * @Version 1.0
 */
@DubboService
@Slf4j
public class OrderServiceImpl implements OrderService {
    @Autowired
    private OrderSettingDao orderSettingDao;
    @Autowired
    private OrderDao orderDao;

    @Override
    @Transactional
    public Order add(Order order) {
        //查询预约设置信息，如果预约日期预约信息不存在不可预约，存在可预约

        OrderSetting orderSetting = orderSettingDao.findByDate(new SimpleDateFormat("yyyy-MM-dd").format(order.getOrderDate()));
        if (null == orderSetting) {
            throw new BusinessRuntimeException(MessageConst.SELECTED_DATE_CANNOT_ORDER);
        } else if (orderSetting.getReservations() >= Integer.parseInt(orderSetting.getNumber())) {
            throw new BusinessRuntimeException(MessageConst.ORDER_FULL);
        }
        //查询是否有重复预约，一人一天一个套餐
        Long count = orderDao.countByMemberAndDateAndSetMeal(order.getMemberId(), order.getOrderDate(), order.getSetmealId());
        if (count > 0) {
            throw new BusinessRuntimeException(MessageConst.HAS_ORDERED);
        }
        //插入预约信息
        orderDao.insert(order);
        //修改已预约数
        orderSettingDao.updateReservationsById(orderSetting.getId(), orderSetting.getReservations() + 1);

        return orderDao.findById(order.getId());
    }

    @Override
    public Order findById(Integer id) {
        return orderDao.findById(id);
    }
}
